﻿using Dapper;
using Inventorycount.API.Read.Application.Command;
using Inventorycount.Dto;
using Inventorycount.ErrorCode;
using MediatR;
using System.Data;
using System.Linq;
using System.Text;

namespace Inventorycount.API.Read.Application.CommandHandLer
{
    public class GetInventoryCommandHandLer : IRequestHandler<GetInventoryCommand, APIPaing<InventoryDto>>
    {

        private readonly IDbConnection repository;

        public GetInventoryCommandHandLer(IDbConnection repository)
        {
            this.repository = repository;
        }
        public async Task<APIPaing<InventoryDto>> Handle(GetInventoryCommand request, CancellationToken cancellationToken)
        {
            APIPaing<InventoryDto> result = new APIPaing<InventoryDto>();
            result.Code = ResultCode.Ok;
            result.Message = "查询成功";

            try
            {
                // 构建SQL查询语句
                var sql = new StringBuilder(@"
                   SELECT 
                    w.Id ,
                    w.Name ,
                    w.Address,
                    w.Status,
                    g.Id AS GoodsId,
                    g.Name  AS  GoodsName, 
                    g.Specification ,
                    u.Id AS UserId,
                    u.Name AS UserName,
                    u.DepaName ,
                    gw.Quantity
                FROM
                    Wms_Inventory gw
                INNER JOIN
                    Wms_Goods g ON gw.GoodsId = g.Id
                INNER JOIN
                    Wms_Warehouse w ON gw.WarehouseId = w.Id
                LEFT JOIN
                    Wms_User u ON w.CreateId = u.Id");
                var parameters = new DynamicParameters();
                // 3. 修正分页查询
                sql.Append(" ORDER BY w.Id ASC");
                sql.Append(" LIMIT @Offset, @PageSize");
                parameters.Add("Offset", (request.PageIndex - 1) * request.PageSize);
                parameters.Add("PageSize", request.PageSize);

                // 4. 修正COUNT查询
                var countSql = new StringBuilder(@"
            SELECT COUNT(*)
                    FROM 
                        Wms_Inventory gw
                    INNER JOIN 
                        Wms_Goods g ON gw.GoodsId = g.Id
                    INNER JOIN 
                        Wms_Warehouse w ON gw.WarehouseId = w.Id
                    LEFT JOIN 
                        Wms_User u ON w.CreateId = u.Id;");
                // 执行查询
                var count = await repository.ExecuteScalarAsync<int>(countSql.ToString(), parameters);
                // 使用Dapper的多映射功能
                var data = await repository.QueryAsync<InventoryDto>(sql.ToString(), parameters);


                result.Data = data.ToList();
                result.TotalCount = count;
                result.TotalPage = (int)Math.Ceiling(count * 1.0 / request.PageSize);
                result.Message = "查询成功";
            } 
            catch (Exception ex)
            {
                result.Code = ResultCode.Fail;
                result.Message = $"查询失败: {ex.Message}";
            }

            return result;
        }
    }
}
